<?php
namespace PsiFramework\Applications\AlloMediaUser\Classes\Actions;

import("Applications.AlloMediaUser.Classes.Actions.ShopAction");
import("Classes.Util.HTTP.AuthenticationManager");
import("Classes.Factory.DAOFactory");
import("Plugins.Shop.Classes.Model.Order");

use \PsiFramework\Applications\AlloMediaUser\Classes\Actions\ShopAction;
use \PsiFramework\Applications\AlloMediaPortal\Classes\Model\InformationPart;
use \PsiFramework\Classes\Util\HTTP\AuthenticationManager;
use \PsiFramework\Classes\Util\HTTP\HTTPRequest;
use \PsiFramework\Classes\Util\HTTP\Session;
use \PsiFramework\Classes\Util\Parameters\Action\ActionParameters;
use \PsiFramework\Classes\Util\UI\HTML;
use \PsiFramework\Classes\Util\Object\Date;
use \PsiFramework\Classes\Factory\DAOFactory;
use \PsiFramework\Plugins\Shop\Classes\Model\Order;
use \PsiFramework\Plugins\PDF\Classes\Tools\PdfFile;
use \PsiFramework\Classes\Util\UI\LanguageManager;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * Classe d'action de l'index
 *
 * @package Actions.Pages
 */
class PdfShowInvoiceAction extends ShopAction
{

    public function __construct(ActionParameters $actionParameters)
    {
        parent::__construct($actionParameters);
    }

    /**
     * The main function of the method which is called every time
     * an action is created by the front controller.
     *
     */
    public function execute()
    {
        parent::execute();
        
        $orderId = $this->_request->getParameter('order_id');
        
        $orderDao = DAOFactory::getDAO('Order');
        $order = $orderDao->retrieveByPk($orderId);
        $currencySymbol = $order->getCurrency()->getSymbol();
        
        $user = $this->_response->getAttribute("user");
        
        $languageManager = LanguageManager::getInstance();
        
        $recalculate=false;
        $title = $languageManager->getText('INVOICE');
        if (!$order->ispaid()) {
        	$title = $languageManager->getText('ORDER');
        	$recalculate=true;
        }
        $orderArray = ShopAction::getOrder($order, $recalculate);
        
        $elements = '';
        $i = 1 ;
        foreach ($orderArray['items'] as $item) {
        	
            $elements .= '<tr>'."\n";
            $elements .= '    <td class="col0 tableTexte">'.$i.'</td>'."\n";
            $elements .= '    <td class="col1 tableTexte">'."\n";
            $elements .=           $item['itemName'];
            
            if (!isNullOrEmptyString($item['itemSubtext'])) {
                $elements .= '<br/>';
                $elements .= '<sub>'.$item['itemSubtext'].'</sub>';
            }
            
            $elements .= '    </td>'."\n";
            $elements .= '    <td class="col3 tableTexte">'.$item['quantityLabel'].'</td>'."\n";
            $elements .= '    <td class="col4 tableTexte">'.number_format($item['realSubTotal'], 2, '.', ' ').$currencySymbol.'</td>'."\n";
            $elements .= '</tr>'."\n";
            $i++;
        }
        
        $taxes = '';
        foreach ($orderArray['taxes'] as $tax) {
            $taxes .= '<tr>';
            $taxes .=     '<td><b>'.$tax['tax']->getName().' ('.number_format($tax['value'], 2, '.', '').'%)</b></td>';
            $taxes .=     '<td class="prix">';
            $taxes .=         ''.number_format($tax['total'], 2, '.', ' ').$currencySymbol;
            $taxes .=     '</td>';
            $taxes .= '</tr>';
        }
        
        $html = file_get_contents(getApplicationDirectory('AlloMediaPortal').'/Template/html/main/profile/invoice.print.php');
        
        $html = str_replace('<include-orderText/>', $languageManager->getText('ORDER'), $html);
        $html = str_replace('<include-dateText/>', $languageManager->getText('DATE'), $html);
        $html = str_replace('<include-paymentText/>', $languageManager->getText('PAYMENT'), $html);
        $html = str_replace('<include-invoiceAddressText/>', $languageManager->getText('INVOICE_ADDRESS'), $html);
        $html = str_replace('<include-productText/>', $languageManager->getText('PRODUCT'), $html);
        $html = str_replace('<include-subscriptionLengthText/>', $languageManager->getText('SUBSCRIPTION_LENGTH'), $html);
        $html = str_replace('<include-priceText/>', $languageManager->getText('PRICE'), $html);
        $html = str_replace('<include-priceWoTaxesText/>', $languageManager->getText('PRICE_WO_TAXES'), $html);
        $html = str_replace('<include-priceWTaxesText/>', $languageManager->getText('PRICE_W_TAXES'), $html);
        
        $html = str_replace('<include-invoiceNumber/>', $order->getNumber(), $html);
        $html = str_replace('<include-orderNumber/>', $order->getNumber(), $html);
        $html = str_replace('<include-invoiceDate/>', $orderArray['date'], $html);
        $html = str_replace('<include-invoicePayment/>', $languageManager->getText($orderArray['mean']), $html);
        $html = str_replace('<include-invoiceName/>', $orderArray['customerName'], $html);
        $html = str_replace('<include-invoiceAddress/>', $orderArray['customerAddress'], $html);
        $html = str_replace('<include-invoiceCity/>', $orderArray['customerZipCode'].' '.$orderArray['customerCity'], $html);
        $html = str_replace('<include-invoiceElements/>', $elements, $html);
        $html = str_replace('<include-invoiceTotalHT/>', number_format($orderArray['realTotal'], 2, '.', ' ').$currencySymbol, $html);
        $html = str_replace('<include-invoiceTaxes/>', $taxes, $html);
        $html = str_replace('<include-invoiceTotalTtc/>', number_format($orderArray['paymentTotal'], 2, '.', ' ').$currencySymbol, $html);
        $html = str_replace('<include-orderTitle/>', $title, $html);
                
        $pdfFile = new PdfFile('utf-8', 'A4', 12);
        $pdfFile->SetDisplayMode('fullpage');
        
        // LOAD a stylesheet
        $stylesheet
            = file_get_contents(
                getApplicationDirectory('AlloMediaUser').'/Template/styles/print.css'
            );
        
        $pdfFile->WriteHTML($stylesheet, 1);
        
        $pdfFile->WriteHTML($html);
        $pdfFile->Output('invoice_'.$order->getNumber().'.pdf', 'I');
        
        exit;
    }
}
